/**
 * 手动打包脚本 - 绕过 electron-builder 的签名问题
 */

const fs = require('fs-extra');
const path = require('path');
const { execSync } = require('child_process');

const ROOT_DIR = path.join(__dirname, '..');
const DIST_DIR = path.join(ROOT_DIR, 'dist');
const ELECTRON_DIR = path.join(ROOT_DIR, 'electron');
const OUTPUT_DIR = path.join(ROOT_DIR, 'build-output');
const APP_DIR = path.join(OUTPUT_DIR, 'P2P下载工具');

async function build() {
  console.log('🚀 开始手动打包...\n');
  
  // 1. 确保 dist 目录存在
  if (!fs.existsSync(DIST_DIR)) {
    console.log('❌ 请先运行: npm run build');
    process.exit(1);
  }
  
  // 2. 清理输出目录
  console.log('🧹 清理旧的输出目录...');
  await fs.remove(OUTPUT_DIR);
  await fs.ensureDir(APP_DIR);
  
  // 3. 复制 node_modules/electron/dist
  console.log('📦 复制 Electron 运行时...');
  const electronPath = path.join(ROOT_DIR, 'node_modules/electron/dist');
  
  if (!fs.existsSync(electronPath)) {
    console.log('❌ Electron 未安装，请运行: npm install');
    process.exit(1);
  }
  
  await fs.copy(electronPath, APP_DIR);
  
  // 4. 创建 resources/app 目录
  console.log('📁 创建应用目录结构...');
  const appResourcesDir = path.join(APP_DIR, 'resources', 'app');
  await fs.ensureDir(appResourcesDir);
  
  // 5. 复制应用文件
  console.log('📋 复制应用文件...');
  
  // 复制 dist
  await fs.copy(DIST_DIR, path.join(appResourcesDir, 'dist'));
  
  // 复制 electron
  await fs.copy(ELECTRON_DIR, path.join(appResourcesDir, 'electron'));
  
  // 复制 node_modules（只复制必需的）
  console.log('📚 复制依赖包...');
  const nodeModulesDir = path.join(appResourcesDir, 'node_modules');
  await fs.ensureDir(nodeModulesDir);
  
  const requiredModules = ['axios', 'pinia', 'vue'];
  for (const mod of requiredModules) {
    const srcPath = path.join(ROOT_DIR, 'node_modules', mod);
    const destPath = path.join(nodeModulesDir, mod);
    if (fs.existsSync(srcPath)) {
      await fs.copy(srcPath, destPath);
      console.log(`  ✓ ${mod}`);
    }
  }
  
  // 创建 package.json
  console.log('📝 创建 package.json...');
  const packageJson = {
    name: 'download-tool',
    version: '1.0.0',
    main: 'electron/main.cjs'
  };
  await fs.writeJSON(path.join(appResourcesDir, 'package.json'), packageJson, { spaces: 2 });
  
  // 6. 重命名 electron.exe
  console.log('🔧 重命名可执行文件...');
  const electronExe = path.join(APP_DIR, 'electron.exe');
  const appExe = path.join(APP_DIR, 'P2P下载工具.exe');
  if (fs.existsSync(electronExe)) {
    await fs.rename(electronExe, appExe);
  }
  
  console.log('\n✅ 打包完成！');
  console.log(`📍 位置: ${APP_DIR}`);
  console.log(`🚀 运行: ${appExe}\n`);
  
  // 7. 创建启动脚本
  const startBat = path.join(OUTPUT_DIR, '启动P2P下载工具.bat');
  await fs.writeFile(startBat, `@echo off
cd /d "%~dp0"
start "" "P2P下载工具\\P2P下载工具.exe"
`);
  
  console.log('💡 提示:');
  console.log('   - 可以直接运行 P2P下载工具.exe');
  console.log('   - 或双击 启动P2P下载工具.bat');
  console.log('   - 整个文件夹可以复制到其他电脑使用\n');
}

build().catch(err => {
  console.error('❌ 打包失败:', err);
  process.exit(1);
});

